<?php

namespace addons\shopro\console;


use app\admin\model\shopro\user\User as UserModel;
use think\Db;
use think\Log;
use Workerman\Timer;
use think\console\Input;
use think\console\Output;

// 定时解绑会员关系
class ShoproUnbindTask extends Command
{

    protected $input = null;
    protected $output = null;

    /**
     * 帮助命令配置
     */
    protected function configure()
    {
        $this->setName('shopro:unbind_notlevel')
            ->setDescription('每日解除未消费的非会员推荐关系');
    }

    public function execute(Input $input, Output $output)
    {
        try {
            // 步骤1：获取需要校验的用户范围（使用EXISTS优化查询）
            $expireDate = strtotime('-30 days');

            $query = UserModel::alias('u')
                ->whereNotNull('parent_user_id')
                ->where('parent_user_time', '<=', $expireDate);

            // 2. 查询普通会员;后续如果要改分销商逻辑可以改查询条件
            $query->whereNotExists(function ($subQuery) {
                $subQuery->name('shopro_commission_agent')->alias('agent')
                    ->field('1')
                    ->where('agent.user_id = u.id')
                    ->where('agent.level', '>', 1);
            });
            // 3. 排除30天内有订单的用户
            $query->whereNotExists(function ($subQuery) {
                $subQuery->name('shopro_order')->alias('orders')
                    ->field('1')
                    ->where('orders.user_id = u.id')
                    ->where('orders.createtime', 'between time', [
                        Db::raw('u.parent_user_time'),
                        Db::raw('u.parent_user_time + interval 30 day')
                    ]);
            });
            $total = 0;

            // 4. 分批处理数据
            $query->chunk(500, function ($users) use (&$total) {
                $total += count($users);

                foreach ($users as $user) {

                    Db::transaction(function () use ($user) {
                        // 清除绑定关系
                        UserModel::where('id', $user->id)
                            ->update([
                                'parent_user_id' => 0,
                                'unbind_time' => time()
                            ]);
                    });
                }
            });

            // 5. 写入任务日志
            Log::record('unbind', "成功处理 {$total} 条");
        } catch (Throwable $e) {
            $output->writeln("<error>Error: 文件:{$e->getFile()};行:{$e->getLine()};{$e->getMessage()}</error>");
            Log::info('unbind_fail' . $e->getTraceAsString());
        }
    }
}